<template>
  <div class="updateavatar-container">
    <van-image
      width="100%"
      height="100%"
      ref="image"
      fit="cover"
      :src="image"
    />
    <van-nav-bar
      class="avatar-nav-bar"
      left-text="取消"
      right-text="确定"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
  </div>
</template>
<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { uploadAvatar } from '@/api/user'
export default {
  name: 'updateAvatar',
  data () {
    return {
      // 预览的图片
      image: window.URL.createObjectURL(this.file),
      // 裁剪实例
      cropper: null
    }
  },
  props: {
    file: {
      type: File,
      required: true
    }
  },
  methods: {
    // 裁剪之后的图片, 包装成promise
    getCroppedCanvas () {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob((file) => {
          resolve(file)
        })
      })
    },
    // 上传头像
    async onConfirm () {
      // 上传提示
      this.$toast.loading({
        message: '上传中...',
        forbidClick: true,
        duration: 0
      })
      // 获取裁剪之后的图片
      const newFile = await this.getCroppedCanvas()
      console.log(newFile)
      // formdata转化
      const fd = new FormData()
      fd.append('photo', newFile)
      console.log(fd)
      // 发送请求, 上传图片
      await uploadAvatar(fd)
      // 上传成功提示
      this.$toast.success({
        message: '上传成功',
        forbidClick: true
      })
      // 父组件更新头像
      this.$emit('update-avatar', window.URL.createObjectURL(newFile))
      // 关闭弹出层
      this.$emit('close')
    }
  },
  mounted () {
    const image = this.$refs.image.$vnode.elm.children[0]
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  }
}
</script>
<style lang="less">
.updateavatar-container{
  height: 100%;
  .van-image{
    img{
      display: block;
      max-width: 100%;
    }
  }
  .avatar-nav-bar{
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: #000;
    .van-nav-bar__text{
      color: #fff;
    }
  }
}
</style>
